//
//  CAAgreementView.swift
//  yzb
//
//  Created by cyptt on 2021/12/13.
//
/*
 UITextView长按后可以弹出复制 粘贴 放大的那个框框，解决办法如下：

 textView.delegate = self;

 textView.editable = YES;

 然后写代理中的这个方法

 -(BOOL)textViewShouldBeginEditing:(UITextView *)textView

 {

 return NO;

 }

 注意：textView.editable一定要设置成YES
 */

import UIKit
import SnapKit


public class CHAgreementView: UIView,UITextViewDelegate {
    
    
    private let xieyiurl:String = "xieyiurl"
    private var agreementClickCallBack:((_ clickTitle:String) -> ())?
    
    private var contentTitle:String = "我已阅读并同意《用户服务协议》《隐私政策》"  //内容
    private  var clickTitles:[String] = [] //要选择的文字
    private var defaultColor:UIColor? =  UIColor.init(red: 89/255.0, green: 89/255.0, blue: 89/255.0,alpha: 1)
    private var clickColor:UIColor? = UIColor.init(red: 68/255.0, green: 140/255.0, blue: 242/255.0, alpha: 1)
    
    public   lazy var checkBoxBtn = {()-> ClickEdgeInsetsButton in
        let btn:ClickEdgeInsetsButton = ClickEdgeInsetsButton.init(type: UIButton.ButtonType.custom)
    
        let normalImage:UIImage? = UIImage.init(named: "check_box_normal", in: CHBundle.bundle(), compatibleWith: nil)
        let seleftImage:UIImage? = UIImage.init(named: "check_box_selected", in: CHBundle.bundle(), compatibleWith: nil)
        btn.setImage(normalImage, for: UIControl.State.normal)
        btn.setImage(seleftImage, for: UIControl.State.selected)
        btn.addTarget(self, action: #selector(checkBoxClick(btn:)), for: UIControl.Event.touchUpInside)
        return btn
    }()
    
    lazy var textView1 = {()-> UITextView in
        let textView:UITextView = UITextView.init()
        textView.isEditable = true;
        textView.isScrollEnabled = false
        textView.delegate = self
        textView.allowsEditingTextAttributes = false
        
//        textView.isSelectable = false
        
        textView.backgroundColor = UIColor.clear
        let allStrig:NSString = self.contentTitle as NSString;
        textView.text =  allStrig as String
        
        
        let paragraphStyle:NSMutableParagraphStyle = NSMutableParagraphStyle.init()
        paragraphStyle.alignment = NSTextAlignment.center;
        paragraphStyle.lineSpacing  = 5
        paragraphStyle.alignment = NSTextAlignment.left
    
        
        let mutAttString:NSMutableAttributedString = NSMutableAttributedString.init(string: textView.text)
        mutAttString.addAttributes([NSAttributedString.Key.foregroundColor:self.defaultColor!,NSAttributedString.Key.paragraphStyle:paragraphStyle,NSAttributedString.Key.font:UIFont.systemFont(ofSize: 13)], range: NSMakeRange(0, mutAttString.length))


        for i in 0..<self.clickTitles.count{
            let clickT:NSString = self.clickTitles[i] as NSString
            
            let range:NSRange? = allStrig.range(of: clickT as String)
            
            let linkname:String =  xieyiurl + String(i) + "://"
            mutAttString.addAttributes([ NSAttributedString.Key.foregroundColor:self.clickColor!,
                                         NSAttributedString.Key.link:linkname], range: range!)
    
        }

        textView.linkTextAttributes = [NSAttributedString.Key.foregroundColor:self.clickColor!]
        textView.attributedText = mutAttString;
        return textView
    }()

    
    
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
    
        self.config()
    }
    
    

    /*
     初始化
     */
  public  init(contentTile:String,clickTitles:[String],defColor:UIColor?,cliColor:UIColor?){
        
        super.init(frame: CGRect.zero)
    

        self.contentTitle = contentTile
        self.clickTitles = clickTitles
        self.defaultColor = defColor ?? self.defaultColor
        self.clickColor = cliColor ?? self.clickColor
       
        self.config()
    }
    func config(){
        self .addSubview(self.checkBoxBtn)
        self.addSubview(self.textView1)
        
        self.setPosition()
    }
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
}

//MARK: -UITextViewDelegate
extension CHAgreementView{
    public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange) -> Bool {
        let stringScheme:String = URL.scheme!
        

        let lastScheme:String = stringScheme.agreement_endSubstring(num: 1)
        print(lastScheme)
        let index:Int = Int(lastScheme) ?? 0

        if self.agreementClickCallBack != nil{
            self.agreementClickCallBack!(self.clickTitles[index])
            return false
        }

        return false;
    }
    
    
    
    public func textViewShouldBeginEditing(_ textView: UITextView) -> Bool {
        return false
    }
   
   public override func canPerformAction(_ action: Selector, withSender sender: Any?) -> Bool {
        

        if #available(iOS 10, *) {
            if action == #selector(UIResponderStandardEditActions.paste(_:))
                || action == #selector(UIResponderStandardEditActions.select(_:))
                || action == #selector(UIResponderStandardEditActions.selectAll(_:))
                || action == #selector(UIResponderStandardEditActions.copy(_:))
                || action == #selector(UIResponderStandardEditActions.cut(_:))
                || action == #selector(UIResponderStandardEditActions.delete(_:))
            {
                OperationQueue.main.addOperation {
                    UIMenuController.shared.setMenuVisible(false, animated: false)
                }
                
                return false
            }
        } else {
            if action == #selector(paste(_:))
                || action == #selector(select(_:))
                || action == #selector(selectAll(_:))
                || action == #selector(copy(_:))
                || action == #selector(cut(_:))
                || action == #selector(delete(_:))
            {
                OperationQueue.main.addOperation {
                    UIMenuController.shared.setMenuVisible(false, animated: false)
                }
                return false
            }
        }
        
        return false
    }
 
}

//MARK:- target
extension CHAgreementView
{
    

    /*
     通用协议
     */
   public func agreementClick(clouse:@escaping(_ clickTitle:String)-> Void){
        self.agreementClickCallBack = clouse
    }
}

//MARK: - position
extension CHAgreementView{
    func setPosition(){
        
        self.checkBoxBtn.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(0)
            make.top.equalToSuperview().offset(8)
            make.width.height.equalTo(16)
        }
        
        self.textView1.snp.makeConstraints { make in
            make.left.equalTo(self.checkBoxBtn.snp.right).offset(5)
            make.right.equalToSuperview().offset(0)
            make.height.equalToSuperview()
            make.top.equalToSuperview().offset(0)
        }
    }
}

//MARK: target
extension CHAgreementView {
    @objc func checkBoxClick(btn:UIButton){
        btn.isSelected = !btn.isSelected
    }
}


extension String {


    
    /*
     截取从结尾后几位字符
     @num 开始后几位
     */
     func agreement_endSubstring(num:Int)->String{
        let index = self.index(self.endIndex, offsetBy: -num)
        let subCha = self[index..<self.endIndex]
        let subStr = String(subCha)
        return subStr
    }
    
   
    
  
}
